package com.shiyi.design.chain;

/**
 * @author wangzhanshuai
 * @date 2021/2/5 9:14 下午
 * @since 1.0
 */
public class MyFilterChain implements MyFilter {

    private MyFilter[] filters = new MyFilter[0];

    private int pos;

    private int n;

    public MyFilterChain add(MyFilter myFilter) {
        if (n == filters.length) {
            MyFilter[] newFilters = new MyFilter[n + 10];
            System.arraycopy(filters, 0, newFilters, 0, n);
            filters = newFilters;
        }
        filters[n++] = myFilter;
        return this;
    }

    @Override
    public void doFilter(MyRequest request, MyResponse response, MyFilterChain filterChain) {
        // 表示还有Filter还未执行
        if(pos < n) {
            MyFilter filter = filters[pos++];
            filter.doFilter(request, response, this);
        }
    }
}
